package com.ebupt.migu.music.common.record;

import com.ebupt.migu.music.common.constants.RedidKeyConstant;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.roster.entity.RosterBlackEntity;
import com.ebupt.migu.music.roster.entity.RosterWhiteEntity;
import com.ebupt.migu.music.roster.mapper.RosterMapper;
import com.ebupt.migu.music.userGroup.entity.bo.UserGroupBo;
import com.ebupt.migu.music.userGroup.mapper.CrowdMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description 将Redis数据下载至本地
 * @Author liuyangyang@cd.ebupt.com
 * @Date 2020/8/12 23:04
 */
@Slf4j
@Service
public class FileRecordAsync {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SCPAsync scpAsync;
    @Autowired
    private RecordSyncMapper recordSyncMapper;

    /**
     * 短信下发记录
     */
//    @Value("${sms_send_record_path}")
    private String SMS_SEND_RECORD_PATH;

    /**
     * 发送记录
     *
     * @param sid
     * @param gid
     * @param whites
     * @param blacks
     */
    @Async("file_record_executor")
    public void record(String sid, String gid, List<String> whites, List<String> blacks) {

        //
        Map<String, Object> strategyInfo = recordSyncMapper.queryStrategyInfo(sid);


        String today = DateUtil.getDateToday();
        try {
            // "a_10008_80025_" + today + "_" + sid + ".dat"  —— push
            //"a_10008_80026_" + today + "_" + sid + ".dat"  —— 消息通知
            String fileName = "a_10008_80010_" + today + "_" + sid + ".dat";
            log.info("生成文件：{}", fileName);
            String path = SMS_SEND_RECORD_PATH + fileName;
            log.info("文件路径：{}", path);
            // 创建文件
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
                log.info("创建文件");
            }
            // BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
            // 记录白名单
            if (whites != null) {
                for (String white : whites) {
                    log.info("白名单用户：{}", white);
                    bufferedWriter.write(white + "|^|" + sid);
                    bufferedWriter.newLine();
                }
            }
            // 记录圈选出的人群
            Cursor<String> cursor = redisTemplate.opsForSet().scan(gid + "-phone", ScanOptions.NONE);
            while (cursor.hasNext()) {
                String msisdn = cursor.next();
                if (blacks != null && blacks.contains(msisdn)) {
                    continue;
                }
                if (whites != null && whites.contains(msisdn)) {
                    continue;
                }
                log.info("普通用户：{}", msisdn);
                bufferedWriter.write(msisdn + "|^|" + sid);
                bufferedWriter.newLine();
            }
            bufferedWriter.close();
            // 文件传输至ETL服务器
            scpAsync.scpFile(path);
            log.info("当前策略存档完成：{}", sid);
        } catch (Exception e) {
            log.error("存档出错：{}", e.getMessage());
        }
    }


}
